package com.kuang.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.kuang.common.to.es.SkuEsModel;
import com.kuang.common.utils.R;
import com.kuang.gulimall.search.config.GulimallElasticSearchConfig;
import com.kuang.gulimall.search.constant.EsConstant;
import com.kuang.gulimall.search.feign.ProductFeignService;
import com.kuang.gulimall.search.service.MallSearchService;
import com.kuang.gulimall.search.vo.AttrResponseVo;
import com.kuang.gulimall.search.vo.SearchParam;
import com.kuang.gulimall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    /*
    * 从ES中查询数据
    * */
    @Override
    public SearchResult search(SearchParam param) {
        //1,动态构建出查询需要的DSL语句
        SearchResult result = null;

        //1,准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);

        try {
            //2,执行检索请求
            SearchResponse response = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

            //3,分析响应数据封装成我们需要的格式
            result = buildSearchRequest(response,param);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return result;
    }

    /*
    * 将返回的数据封装成待返回的对象
    * */
    private SearchResult buildSearchRequest(SearchResponse response,SearchParam param) {

        SearchResult result = new SearchResult();
        SearchHits hits = response.getHits();
/*                //1，返回商品
        result.setProducts(esModels);
        //2,返回属性
        result.setAttrs();
        //3,返回品牌
        result.setBrands();
        //4,返回分类
        result.setCatalogs();*/

        //从hits中提取数据_source
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits()!=null&&hits.getHits().length>0){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (StringUtils.isNotEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(string);
                }
                esModels.add(esModel);
            }
        }
        //从aggregations中获取聚合的信息
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //1，得到品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            //2,得到品牌名
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            //3,得到品牌图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        //属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //1,得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            //2,得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            //3,得到属性的值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());

            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);

            attrVos.add(attrVo);
        }
        //分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            long catalogId = bucket.getKeyAsNumber().longValue();
            String catalogName = ((ParsedStringTerms) bucket.getAggregations().get("catalog_name_agg")).getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogId(catalogId);
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }


        //1，返回商品
        result.setProducts(esModels);
        //2,返回属性
        result.setAttrs(attrVos);
        //3,返回品牌
        result.setBrands(brandVos);
        //4,返回分类
        result.setCatalogs(catalogVos);

        //5,返回分页,页码，总记录数，总页码
        result.setPageNum(param.getPageNum());
        //5.2总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //5.2总页码-计算
        int totalPages = (int)total%EsConstant.PRODUCT_PAGESIZE == 0?((int)total/EsConstant.PRODUCT_PAGESIZE):((int)total/EsConstant.PRODUCT_PAGESIZE+1);
        result.setTotalPages(totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i=1;i<=totalPages;i++){
            pageNavs.add(i);
        }

        //6,构建面包屑导航功能
        if (param.getAttrs()!=null && param.getAttrs().size()>0){
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(attr -> {
                //1,分析每个attrs传过来的查询参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //attrs=2_5寸：6寸
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (r.getCode()==0){
                    AttrResponseVo data = (AttrResponseVo) r.getmyData("attr", new TypeReference<AttrResponseVo>() {});
                    navVo.setNavName(data.getAttrName());
                }else {
                    navVo.setNavName(s[0]);
                }

                //2,取消了面包屑后，跳转到哪里，将请求地址的url里面的当前置空
                //拿到所有的查询条件，去掉当前。这里还涉及到编码问题，要转编码，系统传过来会被编码一次
                //空格，前端的%20，后端编码为+,所以还要转换数据类型
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                    encode = encode.replace("+","%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                String replace = null;
                replace = param.get_queryString().replace("&attrs=" + encode, "");
                String nowUrl = "http://search.gulimall.com/list.html?"+replace;
                //这个地方字符串的正则判断，是整个句子的匹配，而不是部分匹配
                if (nowUrl.matches("(.*)\\?attrs(.*)")){
                    System.out.println("yes");
                    nowUrl = nowUrl.replace("?attrs="+encode,"");
                }
                navVo.setLink(nowUrl);

                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(collect);
        }

        //品牌，分类，也上面包屑导航
        if (param.getBrandId()!=null&&param.getBrandId().size()>0){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            //TOD 远程
//            navVo.setNavValue();

        }


        return result;
    }

    /*
    * 准备检索请求
    * */
    private SearchRequest buildSearchRequest(SearchParam param){
        //构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //1,构建bool
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 bool-must模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //1.2 bool-filter过滤
        //按照三级分类id查询
        if (param.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        //按照品牌id列表查询
        if (param.getBrandId()!=null&&param.getBrandId().size()>0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
        //按照是否有库存查询,这里1是true，0是false,
        if (param.getHasStock()!=null){
        boolQuery.filter(QueryBuilders.termQuery("hasStock",param.getHasStock()==1));
        }
        //嵌套子查询
        if (param.getAttrs()!=null&&param.getAttrs().size()>0){
            //path，query(查询条件)，socreModel（是否参与评分）。
            /*attrs=1_5寸：6寸&attrs=2_16G:8G*/
            BoolQueryBuilder nestedboolQuery = QueryBuilders.boolQuery();
            for (String attrStr : param.getAttrs()) {
                //按照数据格式，按_，第一次分割完剩两个。第二次运用后面的进行分割，剩属性列表
                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedboolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedboolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                //每一个必须都得生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedboolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }

        }
        //价格区间
        /*
         * hasStock=0/1
         * skuPrice=1_500/_500/500_
         * brandId=1
         *
         * */
        if (param.getSkuPrice()!=null){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            /*如果前后都有值，就是价格区间，如果只有前或者后，就对应设计*/
            if (s.length==2){
                rangeQuery.gte(s[0]).lte(s[1]);
            }else if (s.length==1){
                if (param.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(s[0]);
                }
                if (param.getSkuPrice().endsWith("_")){
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        //将bool的分类放进去
        sourceBuilder.query(boolQuery);

        /*排序、分页、高亮*/
        //2,1排序
        if (!StringUtils.isEmpty(param.getSort())){
            String sort = param.getSort();
            //sort = hotScore_asc/desc
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }
        /*
        2,2分页  计算，每一页5个 ，size+
        默认就应该是0开头
        * */
        if (param.getPageNum()==null){
            param.setPageNum(1);
        }

        sourceBuilder.from((param.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);


        //2,3高亮
        if (StringUtils.isNotEmpty(param.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }
        /*聚合分析*/

        //1,品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(10);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(10));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(10));
        sourceBuilder.aggregation(brand_agg);

        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catalogId").size(10);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(10));
        sourceBuilder.aggregation(catalog_agg);

        //嵌套聚合
        NestedAggregationBuilder nested_attrs_agg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(10));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10));
        nested_attrs_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(nested_attrs_agg);


        String s = sourceBuilder.toString();
        System.out.println("构建的DSL"+s);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;

    }
}
